package codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
import org.msgpack.MessagePack;
import protocol.NettyMessage;

public class MessagePackDecoder extends LengthFieldBasedFrameDecoder {

    public MessagePackDecoder(int maxFrameLength, int lengthFieldOffset,
        int lengthFieldLength) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
    }

    /*protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf msg, List<Object> list) throws Exception {
        System.out.println("开始解码:"+System.currentTimeMillis());
        int len = msg.readableBytes();//获取数据长度
        byte[] data = new byte[len];
        msg.getBytes(msg.readerIndex(),data,0,len);
        MessagePack pack = new MessagePack();
        NettyMessage message = pack.read(data,pack.lookup(NettyMessage.class));
        list.add(message);
        System.out.println("解码完成:"+System.currentTimeMillis());
    }*/

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("开始解码:"+System.currentTimeMillis());
        int len = msg.readableBytes();//获取数据长度
        byte[] data = new byte[len];
        msg.getBytes(msg.readerIndex(),data,0,len);
        MessagePack pack = new MessagePack();
        NettyMessage message = pack.read(data,pack.lookup(NettyMessage.class));
        //list.add(message);
        System.out.println("解码完成:"+System.currentTimeMillis());
        return message;
    }
}
